﻿using ShenNius.Sys.API.Domain.Entity.Common;
using ShenNius.Sys.API.Infrastructure.Common;
using SqlSugar;
using System;
using System.Linq;

namespace ShenNius.Sys.API.Domain.Entity
{
    [SugarTable("Sys_User")]
    public class User : BaseEntity, IAggregateRoot
    {
        /// <summary>
        /// 登录账号
        /// </summary>
        public string Name { get; private set; }
        /// <summary>
        /// 登录密码
        /// </summary>
        public string Password { get; private set; }

        /// <summary>
        /// 真是姓名
        /// </summary>
        public string TrueName { get; private set; }
        /// <summary>
        /// 头像
        /// </summary>
        public string HeadImg { get; private set; }
        /// <summary>
        /// 性别
        /// </summary>
        public string Sex { get; private set; } = "男";
        /// <summary>
        /// 手机号码
        /// </summary>
        public string Mobile { get; private set; }
        /// <summary>
        /// 邮箱
        /// </summary>
        public string Email { get; private set; }
        /// <summary>
        /// 备注
        /// </summary>
        public string Remark { get; private set; }
        public string Ip { get; private set; }
        public string Address { get; private set; }
        /// <summary>
        /// 当前登录时间
        /// </summary>
        public DateTime? LastLoginTime { get; set; }
        public bool IsLogin { get; set; }

        public void ChangePassword(string password)
        {
            if (string.IsNullOrEmpty(password))
            {
                throw new ArgumentException(nameof(password));
            }
            Password = Md5Crypt.Encrypt(password);
            NotifyModified();
        }
        public void IsEquaPassword(string oldPassword)
        {
            if (string.IsNullOrEmpty(oldPassword))
            {
                throw new ArgumentException(nameof(oldPassword));
            }
            oldPassword = Md5Crypt.Encrypt(oldPassword);
            if (Password != oldPassword)
            {
                throw new ArgumentException("旧密码错误!");
            }

        }
        public void ModifyIpAddress()
        {
            var ip = MyHttpContext.Current.Request.Headers["X-Forwarded-For"].FirstOrDefault() ?? MyHttpContext.Current.Connection.RemoteIpAddress.ToString();
            Ip = ip;
            Address = IpParseHelper.GetAddressByIP(Ip);
        }
        public void ModifyLastLoginTime()
        {
            LastLoginTime = DateTime.Now;
        }
        public void ModifyIsLogin()
        {
            IsLogin = true;
            ModifyLastLoginTime();
        }
        public void Modify(string name, string mobile, string remark, string email, string trueName, string sex)
        {
            Name = name;
            Mobile = mobile;
            Remark = remark;
            Email = email;
            TrueName = trueName;
            Sex = sex;
            NotifyModified();
        }
    }
}
